package test;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class MyHystrixCommand extends HystrixCommand<String> {

    private final String name;

    public MyHystrixCommand(String name) {
        /*super(HystrixCommandGroupKey.Factory.asKey("MyGroup"));
        this.name = name;*/

        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey
                        .Factory.asKey("MyGroup"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionIsolationStrategy(HystrixCommandProperties
                                .ExecutionIsolationStrategy.SEMAPHORE
                        )));
        this.name = name;
    }

    @Override
    protected String run() {
        System.err.println("get data");
        // int num = 1 / 0;
        return this.name + ":" + Thread.currentThread().getName();
    }

    // 回调方法
    @Override
    protected String getFallback() {
        return "失败了 ";
    }

    // 缓存策略
    @Override
    protected String getCacheKey() {
        return String.valueOf(this.name);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        /*String s = new MyHystrixCommand("zhangsan").execute();
        System.out.println(s);

        String s2 = new MyHystrixCommand("zhangsan").execute();
        System.out.println(s2);

        String s1 = new MyHystrixCommand("zhangsan").queue().get();
        System.out.println(s1);*/

        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        String result = new MyHystrixCommand("zhangsan").execute();
        System.out.println(result);
        Future<String> future = new MyHystrixCommand("zhangsan").queue();
        System.out.println(future.get());
        context.shutdown();


    }
}
